package example.avro

import java.io.File

/**
 *
 * @author tzp
 * @since 2021/8/10
 */
object TestAvro {
  def main(args: Array[String]): Unit = {
    val a = "1111111"
    println(s"fadfas$a")
    testWrite
    testRead

  }

  def testWrite: Unit = {
    val user1 = new User
    user1.setName("Alyssa")
    user1.setFavoriteNumber(256)
    // Leave favorite color null

    // Alternate constructor
    val user2 = new User("Ben", 7, "red")

    // Construct via builder
    val user3 = User.newBuilder.setName("Charlie").setFavoriteColor("blue").setFavoriteNumber(null).build

    import org.apache.avro.file.DataFileWriter
    import org.apache.avro.specific.SpecificDatumWriter
    // Serialize user1, user2 and user3 to disk// Serialize user1, user2 and user3 to disk

    val userDatumWriter = new SpecificDatumWriter[User](classOf[User])
    val dataFileWriter = new DataFileWriter[User](userDatumWriter)
    dataFileWriter.create(user1.getSchema, new File("users.avro"));
    dataFileWriter.append(user1)
    dataFileWriter.append(user2)
    dataFileWriter.append(user3)
    dataFileWriter.flush()
    dataFileWriter.close()
  }

  def testRead: Unit = {
    import org.apache.avro.file.DataFileReader
    import org.apache.avro.specific.SpecificDatumReader
    // Deserialize Users from disk// Deserialize Users from disk

    val userDatumReader = new SpecificDatumReader[User](classOf[User])
    val dataFileReader = new DataFileReader[User](new File("users.avro"),
      userDatumReader)
    var user: User = null
    while (dataFileReader.hasNext) { // Reuse user object by passing it to next(). This saves us from
      // allocating and garbage collecting many objects for files with
      // many items.
      user = dataFileReader.next(user)
      println(user)
    }
  }
}
